package com.heima.behavior.service.Imp;

import com.heima.behavior.service.ApArticleBehaviorService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ArticleBehaviorDTO;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class ApArticleBehaviorServiceImp implements ApArticleBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        //对是否登录判断
        HashMap<String, Object> map = new HashMap<>();
        if (user.getId().equals(dto.getEquipmentId())) {
            //未登录状态  所有的值设置为false
            // {"isfollow":true,"islike":true,"isunlike":false,"iscollection":true}
            map.put("isfollow", false);
            map.put("islike", false);
            map.put("isunlike", false);
            map.put("iscollection", false);
            return ResponseResult.okResult(map);
        } else {
            //登陆状态 查询行为实体 token中的登录参数
            Query query = Query.query(Criteria.where("refId").is(user.getId()).and("type").is(1));
            //查询出用户的相关所有行为
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //说明新用户登录  那么用户从未有过行为 需要先对行为进行创建才能有行为
            if (behaviorEntry.getId() == null) {
                ApBehaviorEntry apBehaviorEntry = creatBehaviorEntryMsg(dto);
            }
            //获得参数entryId
            String entryId = behaviorEntry.getId();
            //1.是否关注作者
            Integer loginUserId = AppThreadLocalUtils.getUser().getId();
            Boolean isRelate =  IsRelation(dto.getAuthorApUserId() ,loginUserId);
            map.put("isfollow", isRelate);
            //2.查询是否点赞
            Boolean like = isLike(entryId, dto);
            map.put("islike", like);
            //3.是否不喜欢
            Boolean unLike = isUnLike(entryId, dto);
            map.put("isunlike", unLike);
            //4.是否收藏
            Boolean isConnect = IsConnect(entryId,dto);
            map.put("iscollection", isConnect);
            return ResponseResult.okResult(map);
        }

    }

    private Boolean IsRelation(Integer authorApUserId, Integer loginUserId) {
        boolean flag = true;
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorApUserId));
        //未发现关注就是空
        if (score == null) {
            flag = false;
        }
        return flag;
    }

    private Boolean IsConnect(String entryId, ArticleBehaviorDTO dto) {
        boolean flag = true;
        Query connectQuery = Query.query(Criteria.where("entryId").is(entryId).and("articleId").is(dto.getArticleId()));
        ApCollection isconnect = mongoTemplate.findOne(connectQuery, ApCollection.class);
        if (isconnect == null) {
            flag = false;
        }
        return flag;
    }

    public Boolean isLike(String entryId,ArticleBehaviorDTO dto){
        boolean flag = true;
        Query isLikeQuery = Query.query(Criteria.where("entryId").is(entryId).and("articleId").is(dto.getArticleId()));
        ApLikesBehavior likesBehavior = mongoTemplate.findOne(isLikeQuery, ApLikesBehavior.class);
        if (likesBehavior == null) {
            flag = false;
        }
        return flag;
    }


    public Boolean isUnLike(String entryId,ArticleBehaviorDTO dto){
        boolean flag = true;
        Query isUnLikeQuery = Query.query(Criteria.where("entryId").is(entryId).and("articleId").is(dto.getArticleId()));
        ApUnlikesBehavior unlikesBehavior = mongoTemplate.findOne(isUnLikeQuery, ApUnlikesBehavior.class);
        if (unlikesBehavior == null) {
            flag = false;
        }
        return flag;
    }
    /**
     * 获取行为创建
     * @param dto
     * @return
     */
    private ApBehaviorEntry creatBehaviorEntryMsg(ArticleBehaviorDTO dto) {
        //获得用户token中的id检查是否处于登陆状态
        ApUser user = AppThreadLocalUtils.getUser();
        //对数据进行判空
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户未携带ID或未携带设备ID");
        }
        //调用
        // return  ApBehaviorEntryService(user.getId(),likesBehaviorDTO.getEquipmentId());
        return apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(),dto.getEquipmentId());
    }

}
